<template>
  <q-card>
    <div class="q-pa-sm row items-center h-48px">
      <div class="col text-base">
        <q-input
          v-model="pageParam.query"
          type="text"
          dense
          label="搜索用户"
          outlined
          rounded
          debounce="500"
        />
      </div>
      <div>
        <q-btn
          dense
          flat
          round
          icon="add"
          @click="
            () => {
              userSelectDig = true
            }
          "
        >
          <q-tooltip> 发起新私信 </q-tooltip>
        </q-btn>
      </div>
    </div>
    <q-scroll-area style="width: 300px; height: 414px">
      <q-item
        clickable
        v-for="item in rows"
        :key="item.id"
        :active="receiveUser?.id == item.chatUser.id"
        @click="
          () => {
            clearRed(item)
          }
        "
      >
        <q-item-section top avatar>
          <q-avatar size="38px">
            <q-img
              error-src="/images/default-avatar.png"
              :src="item.chatUser.avatar"
              :ratio="1 / 1"
            />
          </q-avatar>
        </q-item-section>
        <q-item-section>
          <q-item-label>
            {{ item.chatUser.username }}
          </q-item-label>
          <q-item-label caption lines="1">
            <div v-html="item.lastMsg"></div>
          </q-item-label>
        </q-item-section>
        <q-item-section side>
          <div class="row items-center">
            <div v-if="item.showRed" class="w-2 h-2 bg-red rounded"></div>
            <div class="text-xs">{{ item.relativeTime }}</div>
          </div>
        </q-item-section>
        <q-item-section side>
          <q-btn dense flat icon="more_vert" round @click.stop="() => {}">
            <q-menu>
              <q-list dense style="min-width: 60px">
                <q-item
                  clickable
                  v-close-popup
                  @click="
                    () => {
                      chatDel({ id: item.id }).then(({ error }) => {
                        if (!error) {
                          rows = rows.filter((i) => i.id != item.id)
                        }
                      })
                    }
                  "
                >
                  <q-item-section>删除会话</q-item-section>
                </q-item>
                <q-separator />
              </q-list>
            </q-menu>
          </q-btn>
        </q-item-section>
      </q-item>
      <q-item v-show="loading">
        <q-item-section top avatar>
          <q-skeleton type="QAvatar" size="32px" />
        </q-item-section>
        <q-item-section>
          <q-item-label><q-skeleton type="text" /></q-item-label>
          <q-item-label caption lines="1">
            <q-skeleton type="text" />
          </q-item-label>
        </q-item-section>
      </q-item>
      <q-item v-show="!loading && pageParam.recordCount == 0">
        <q-item-section class="text-center"> 无用户 </q-item-section>
      </q-item>
      <div class="row justify-center" v-if="pageParam.totalPage > 1">
        <q-btn
          dense
          :loading="loading"
          flat
          :disable="pageParam.recordCount == 0 || pageParam.pageNum == pageParam.totalPage"
          :label="pageParam.pageNum >= pageParam.totalPage ? '已加载全部' : '加载更多'"
          @click="
            () => {
              pageParam.pageNum++
              load()
            }
          "
        />
      </div>
    </q-scroll-area>
  </q-card>
</template>

<script setup lang="ts">
import { receiveUser, userSelectDig } from './shared'
import type { ApiType } from 'src/service/api'
import { chatDel, chatFlag, chatUser } from 'src/service/api/chat'
import { useWebStore } from 'src/stores/webStore'
import { onMounted, ref, inject, watch } from 'vue'
import type { EventBus } from 'quasar'
import { eventBusKey, MsgType } from 'src/use'

const bus = inject(eventBusKey) as EventBus<Api.EventBusType>

const pageParam = ref({
  query: '',
  order: 'create_time',
  pageNum: 1,
  pageSize: 20,
  totalPage: 0,
  recordCount: 0,
})

watch(
  () => pageParam.value.query,
  (val) => {
    pageParam.value.query = val
    f5()
  },
)

const webStore = useWebStore()

const { refreshTag } = webStore

type rowType = ApiType<typeof chatUser>['Return']['rows'][0]
const rows = ref<Array<rowType>>([])

const addChatUser = (newChatUser: rowType) => {
  const last = rows.value.findLast((i) => i.id == newChatUser.id)
  if (!last) {
    rows.value.push(newChatUser)
  }
}
const loading = ref(false)

const f5 = () => {
  pageParam.value.pageNum = 1
  rows.value = []
  load()
  refreshTag()
}

const load = () => {
  loading.value = true
  chatUser(pageParam.value).then(({ data, error }) => {
    loading.value = false
    if (!error) {
      rows.value.push(...data.rows)
      pageParam.value.pageNum = data.pageNum
      pageParam.value.pageSize = data.pageSize
      pageParam.value.totalPage = data.totalPage
      pageParam.value.recordCount = data.recordCount
    }
  })
}

const clearRed = (item: rowType) => {
  receiveUser.value = item.chatUser
  chatFlag({ userId: receiveUser.value.id }).then(({ error }) => {
    if (!error) {
      item.showRed = false
      refreshTag()
    }
  })
}

onMounted(() => {
  f5()
  refreshTag()
  bus.on(MsgType.refreshChat, () => {
    f5()
  })
})

defineExpose({
  addChatUser,
})
</script>

<style scoped></style>
